﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Warensoft.Unity.Communication.Client.Contracts;

namespace Warensoft.Unity.Communication.Client
{
    public class WarensoftPackageManager : PackageManagerBase
    {
        private short lastPackageLength = 0;
        protected override object[] ProcessQueueToPackage()
        {

            List<MessageBase> result = new List<MessageBase>();
            while (this.messageQueue .Count !=0)
            {
                var buffer = this.messageQueue.ToArray();
                using (MemoryStream ms = new MemoryStream(buffer))
                {

                    using (BinaryReader br = new BinaryReader(ms))
                    {

                        //package length(short)|content

                        if (lastPackageLength == 0)
                        {
                            if (ms.Length < 2)
                            {
                                break;
                            }

                            this.lastPackageLength = br.ReadInt16();
                            this.RemoveFromQueue(2);
                        }
                        if (ms.Length < this.lastPackageLength)
                        {
                            break;
                        }
                        byte[] buffer1 = new byte[this.lastPackageLength];
                        br.Read(buffer1, 0, buffer1.Length);
                        this.RemoveFromQueue(buffer1.Length);
                        result.Add(new WarensoftMessage(buffer1));
                        this.lastPackageLength = 0;
                    }
                }
            }


            return result.ToArray();

        }

    }
}
